<template>
  <div class="videoPlayer" ref="videoPlayer">
    <div class="m-8">
      <!-- vue3VideoPlay 组件的实现细节未提供，这里假设它是一个自定义的视频播放组件 -->
      <!--      @canplay="onCanplay"-->
      <transition
          name="fade"
      >
        <vue3VideoPlay
            v-bind="options"
            :poster="options.poster"
            autoplay
            @play="onPlay"
            @pause="onPause"
            @timeupdate="onTimeupdate"
            @keydown="handleKeyDown"
            @ended="handleEnded"
        />
      </transition>
    </div>
    <!-- 点赞、收藏、评论、分享和用户头像的图标和文本 -->
    <div class="Like">
      <div style="display: flex;align-items: center">
        <i class="iconfont icon-dianzan" style="color: #fff; font-size: 25px; margin-bottom: 5px"></i>
      </div>
      <span style="color: #fff">{{ collectSize }}</span>
    </div>
    <div class="Like1">
      <div style="display: flex;align-items: center" @click="handleCollect">
        <i
            :class="{'iconfont icon-shoucang': true, 'collected': isCollect === 1}"
            style="font-size: 25px; margin-bottom: 5px"
        ></i>
      </div>
      <span style="color: #fff">{{ collectSize }}</span>
    </div>
    <div class="Like3" @click="openDrawer">
      <i class="iconfont icon-pinglun" style="color: #fff; font-size: 25px; margin-bottom: 5px"></i>
    </div>
    <div class="Like4">
      <i class="iconfont icon-fenxiang" style="color: #fff; font-size: 25px; margin-bottom: 5px" @click="handleShare"></i>
      <!--      <span style="color: #fff" >分享</span>-->
    </div>
    <div class="Like5">
      <!-- el-avatar 和 el-icon 需要从 element-plus 导入 -->
      <el-avatar :src="Alerts.UserInfo.user.avatar"></el-avatar>
      <!--      <el-icon style="color: #fff; border: 2px solid #ccc; border-radius: 50%; font-size: 20px;">-->
      <!--        &lt;!&ndash; Plus 组件的实现细节未提供，这里假设它是一个自定义图标组件 &ndash;&gt;-->
      <!--        <Plus/>-->
      <!--      </el-icon>-->
    </div>
    <el-drawer
        title="视频评论"
        v-model="drawer"
        size="40%"
        @close="handleClose"
    >
      <!-- 评论列表 -->
      <div class="comment-container" v-for="(comment, index) in comments" :key="index">
        <div class="comment-user">
          <el-avatar :src="comment.avatar"/> <!-- 假设每个评论都有对应的头像链接 -->
          <span class="comment-username">{{ comment.username }}</span>
        </div>
        <div class="comment-content">
          <p>{{ comment.content }}</p>
        </div>
        <el-button plain type="primary" v-if="Alerts.UserInfo.user.id === comment.userId"
                   @click="handleDelete(comment.id)">删除评论
        </el-button>
      </div>

      <!-- 评论输入区域 -->
      <div class="comment-input-container">
        <el-input
            type="textarea"
            rows="2"
            placeholder="写下你的评论..."
            v-model="newComment"
            class="comment-textarea"
        />
        <el-button type="primary" @click="submitComment" class="comment-submit">提交</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {useAlertsStore} from "../../store/modules/home.js";
import {
  reqUserCommentSave,
  reqUserCommentList,
  reqUserCollectSave,
  reqUserCommentDelete,
  reqUserCollectUpdataSave,
  reqVedioInfoByIdList,
  reqVedioInfoByIdDelete,
  reqVedioDeleteCollect
} from '@/api/home'
import {findMyCollectByUserId} from "@/api/manage.js";
import {ref, onMounted, watch, nextTick, defineEmits} from "vue";

const emit = defineEmits(['getList'])
import {ElMessage} from "element-plus";
import _ from "lodash";
import {useCopyToClipboard} from '@/hooks/clipBoard'
const {copyToClipboard} = useCopyToClipboard()
let props = defineProps(['recommendList'])
// import 'animate.css';
let videoPlayer = ref(null);
const videoType = ref('')
const videoId = ref('')
const collectSize = ref(0)
const isCollect = ref(0)
watch(() => props.recommendList, (newVal, oldVal) => {
  nextTick(async () => {
      if(Alerts.UserInfo.user){
        let res =  await findMyCollectByUserId(Alerts.UserInfo.user.id)
        // let result = await reqUserUserLikeList()
        const userCollect = res.list || []
        recommendList.value = newVal;
        recommendList.value.forEach(item=> {
          userCollect.forEach(i => {
            if(item.id ===  i.id){
              item.isCollect = 1
            }else{
              item.isCollect = 0
            }
          })
        })
      }else {
        recommendList.value = newVal;
        recommendList.value.forEach(item=>{
          item.isCollect = 0
        })
      }
    // 将索引重置为0，并更新视频源
    index.value = 0;
    options.value.src = recommendList.value[0]?.videoUrl || '';
    videoId.value = recommendList.value[0]?.id || ''
    videoType.value = recommendList.value[0]?.videoType || ''
    collectSize.value = recommendList.value[0]?.collectSize || 0
    isCollect.value = recommendList.value[0]?.isCollect || 0
  });
});

const shuffle = (array) => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
let Alerts = useAlertsStore();
// let currentTime = 0;
const options = ref({
  width: "900px", //播放器宽度
  height: "550px", //播放器高度
  color: "#409eff", //主题色
  src: "", //视频源
  poster: "", // 视频封面
  muted: true, //静音
  speed: true, // 关闭进度条拖动
  webFullScreen: false,
  speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
  autoPlay: true, //自动播放
  loop: false, //循环播放
  mirror: false, //镜像画面
  ligthOff: false, //关灯模式
  volume: 0.3, //默认音量大小
  control: true, //是否显示控制
  controlBtns: [
    "audioTrack",
    "quality",
    "speedRate",
    "volume",
    "setting",
    "pip",
    "pageFullScreen",
    "fullScreen",
  ], //显示所有按钮,
});
watch(() => options.value.src, () => {
  reqUserComment()
})
let recommendList = ref({});
/**
 * 支持所有原生video事件
 */

let index = ref(0);
onMounted(() => {
  window.addEventListener("keydown", handleKeyDown);
});
const onPlay = () => { /* ... */
};
const onPause = () => { /* ... */
};
const onTimeupdate = (e) => {
  // 假设 e.target 是视频元素
  localStorage.setItem("currentTime", e?.target.currentTime.toString());
};

const handleShare = () => {
  copyToClipboard(options.value.src);
}

const handleKeyDown = (event) => {
  if (!props.recommendList.length) return;

  let newIndex;
  switch (event.keyCode) {
    case 83: // Down arrow - 下一个视频
      if (index.value === props.recommendList.length - 1) {
        // 如果已经到达列表的最后一个视频，显示提示信息
        ElMessage({
          message: "没有更多了",
          type: "warning",
        });
      } else {
        // 如果不是最后一个视频，正常增加索引
        newIndex = index.value + 1;
      }
      break;
    case 87: // Up arrow - 上一个视频
      if (index.value === 0) {
        ElMessage.warning('已经到最顶部了')
      } else {
        newIndex = index.value - 1;
      }
      break;
    default:
      return; // 确保在default情况下不执行任何操作
  }

  if (typeof newIndex !== 'undefined') {
    // 确保新的索引在有效范围内
    newIndex = Math.max(0, Math.min(newIndex, props.recommendList.length - 1));
    index.value = newIndex;
    event.preventDefault();
    updateVideoSource();
  }
};

const updateVideoSource = async () => {
  if (index.value === props.recommendList.length - 1) {

  }
  if (index.value <= props.recommendList.length) {
    const videoItem = props.recommendList[index.value];
    // videoPlayer.value.classList.add("animation-effect");

    // 更新视频源和封面
    options.value.src = videoItem.videoUrl;
    options.value.poster = videoItem.videoHover;
    videoId.value = videoItem.id
    videoType.value = videoItem.videoType
    // collectSize.value = videoItem.collectSize
    isCollect.value = videoItem.isCollect
    const videoInfo =  await reqVedioInfoByIdList(videoId.value)
    collectSize.value = videoInfo.video.collectSize
    // 重置当前播放时间
    const videoElement = videoPlayer.value // 假设videoPlayer包含video元素
    videoElement.currentTime = 0;
    // 重新加载视频，如果vue3VideoPlay组件提供了load方法
    if (videoPlayer.value.load) {
      videoPlayer.value.load();
    }

    // 播放视频
    // videoElement.play();

    setTimeout(() => {
      // videoPlayer.value.classList.remove("animation-effect");
    }, 1000);
  } else {
    ElMessage({
      message: "没有更多了",
      type: "warning",
    });
  }
};

const drawer = ref(false);

// 模拟评论数据
const comments = ref([]);

// 新评论内容
const newComment = ref('');


const reqUserComment = async () => {
  let res = await reqUserCommentList(videoId.value)
  comments.value = res.commentVoList
}
// 打开抽屉
const openDrawer = async () => {
  if(!Alerts.UserInfo.user){
    ElMessage.warning('登录后享用此功能!!!')
    return
  }else {
    reqUserComment()
    drawer.value = true;
  }

};

// 关闭抽屉时的钩子
const handleClose = () => {
  // 可以在这里执行一些关闭抽屉时的操作
  newComment.value = ''
  comments.value = []
};
// 提交评论
const submitComment = async () => {
  if (!Alerts.UserInfo.user.id) {
    ElMessage.warning('请先登录在进行评论')
    return
  }
  if (newComment.value.trim()) {
    await reqUserCommentSave({
      videoId: videoId.value,
      userId: Alerts.UserInfo.user.id,
      content: newComment.value
    })
    newComment.value = ''
    ElMessage.success('评论成功')
    await reqUserComment()
  } else {
    ElMessage.warning('评论内容不能为空！');
  }
};


const handleCollect = async () => {
  if(!Alerts.UserInfo.user){
    ElMessage.warning('登录后享用此功能!!!')
    return
  }
  const videoInfo =  await reqVedioInfoByIdList(videoId.value)
  let updateVideo
  recommendList.value.forEach(item => {
    if(item.id === videoInfo.video.id){
      updateVideo = item
    }
  })
  if (isCollect.value === 0) {
    await reqUserCollectUpdataSave({
      videoId: videoId.value,
      userId: Alerts.UserInfo.user.id,
      typeId: videoType.value,
      status: 2,
    })
    await reqUserCollectSave({
      id: videoId.value,
      userId: Alerts.UserInfo.user.id,
      typeId: videoType.value,
      status: 2,
      collectSize: collectSize.value + 1
    })
    const videoInfo =  await reqVedioInfoByIdList(videoId.value)
    updateVideo.isCollect = 1
    isCollect.value = 1
    collectSize.value = videoInfo.video.collectSize
  }else {
    await reqVedioInfoByIdDelete(
      [videoId.value].join(',')
    ).then(res => {
      // console.log(res, '删除的接口')
    })
    await reqUserCollectSave({
      id: videoId.value,
      userId: Alerts.UserInfo.user.id,
      typeId: videoType.value,
      status: 2,
      collectSize: collectSize.value === 0 ? 0 : collectSize.value - 1
    })
    const videoInfo =  await reqVedioInfoByIdList(videoId.value)
    collectSize.value = videoInfo.video.collectSize
    updateVideo.isCollect = 0
    isCollect.value = 0
  }
}

// 删除评论的接口
const handleDelete = async (id) => {
  await reqUserCommentDelete([id])
  reqUserComment()
  ElMessage.success('删除成功')
}


const handleEnded = () => {
  console.log(11111)
  // 如果已经在最后一个视频，不执行任何操作
  if (index.value >= props.recommendList.length - 1) {
    ElMessage.warning('没有更多了!!!')
    return;
  }
  // 否则，切换到下一个视频
  index.value++;
  updateVideoSource(); // 调用已有的方法来更新视频源
};
</script>


<style scoped lang="less">
.m-8 {
  background-color: pink;
  margin-top: -20px;
  margin-left: 80px;
  border-radius: 8px;
}

.videoPlayer {
  position: relative;
  border-radius: 10px;
}

/* 定义fade过渡的样式 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 1s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.Like,
.Like1,
.Like3,
.Like4,
.Like5 {
  cursor: pointer;
  position: absolute;
  z-index: 999;
  bottom: 20px;
  right: 0px;
}

.Like {
  bottom: 230px;
}

.Like1 {
  bottom: 170px;
}

.Like3 {
  bottom: 130px;
}

.Like4 {
  bottom: 90px;
}

.Like5 {
  bottom: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

@keyframes slide {
  from {
    opacity: 0;
    transform: translateY(-100px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animation-effect {
  animation: slide 1.5s ease;
}

:deep(.d-play-btn[data-v-01791e9e] ) {
  width: 90px;
  height: 90px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000000b3;
  border-radius: 50%;
  display: none;
}


.el-drawer {
  overflow: auto;
  margin-top: 10px;
}

/* 评论列表样式 */
.comment-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  padding: 10px;
  border-bottom: 1px solid #eaeaea;
}

.comment-user {
  margin-right: 10px;
}

.comment-username {
  display: block;
  font-weight: bold;
}

.comment-content {
  flex-grow: 1; /* 占据剩余空间 */
  display: flex; /* 使用 Flexbox 布局 */
  flex-direction: column; /* 使子元素垂直排列 */
  justify-content: center; /* 垂直居中 */
  text-align: left; /* 确保文本向左对齐 */
}

/* 评论输入区域样式 */
.comment-input-container {
  display: flex;
  align-items: center;
  justify-content: center;
  //flex-direction: column;
  margin-top: 20px;
}

.comment-textarea {
  margin-right: 10px;
}

.comment-submit {
  align-self: flex-end;
}

/* 其他样式调整 */
:deep(.el-avatar) {
  width: 40px;
  height: 40px;
}

/* 其他样式保持不变 */

.collected {
  color: red !important; /* 浅蓝色，确保这个颜色覆盖其他样式 */
}
</style>
